import React, { useState, useEffect } from 'react';
import { Table, Card, Form, Input, Select, Space, Button, message } from 'antd';
import type { TablePaginationConfig } from 'antd/es/table';
import { DownloadOutlined } from '@ant-design/icons';
import { getPartyFees, exportPartyFees } from '@/api/partyFee';
import type { PartyFee, PartyFeeQueryDTO } from '@/api/partyFee';
import dayjs from 'dayjs';

const initialSearchParams: PartyFeeQueryDTO = {
  page: 1,
  size: 10,
  keyword: '',
  className: '',
  position: '',
  year: new Date().getFullYear(),
};

const PartyFeeResult: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<PartyFee[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchParams, setSearchParams] = useState<PartyFeeQueryDTO>(initialSearchParams);

  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize, searchParams]);

  const fetchData = async () => {
    try {
      setLoading(true);
      const params: PartyFeeQueryDTO = {
        ...searchParams,
        page: pagination.current,
        size: pagination.pageSize,
      };

      const result = await getPartyFees(params);
      setData(result.records);
      setPagination(prev => ({
        ...prev,
        total: result.total,
      }));
    } catch (error) {
      // 错误已在request.ts中处理
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = async () => {
    try {
      const values = await form.validateFields();
      setSearchParams({
        ...initialSearchParams,
        ...values,
      });
      setPagination(prev => ({ ...prev, current: 1 }));
    } catch (error) {
      // 错误已在request.ts中处理
    }
  };

  const handleReset = () => {
    form.resetFields();
    setSearchParams(initialSearchParams);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  const handleExport = async () => {
    try {
      const values = await form.validateFields();
      const params: PartyFeeQueryDTO = {
        ...values,
      };
      const response = await exportPartyFees(params);
      
      // 创建Blob对象
      const blob = new Blob([response], { type: 'application/vnd.ms-excel' });
      
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `党费计算结果_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`;
      
      // 触发下载
      document.body.appendChild(link);
      link.click();
      
      // 清理
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      message.success('导出成功');
    } catch (error) {
      // 错误已在request.ts中处理
    }
  };

  const columns = [
    {
      title: '所在班级',
      dataIndex: 'className',
      key: 'className',
    },
    {
      title: '职务',
      dataIndex: 'position',
      key: 'position',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '身份证号',
      dataIndex: 'idCard',
      key: 'idCard',
    },
    {
      title: '标识号',
      dataIndex: 'identifier',
      key: 'identifier',
    },
    {
      title: '计算年月',
      dataIndex: 'calculationDate',
      key: 'calculationDate',
      render: (date: string) => date ? dayjs(date).format('YYYY年MM月') : '-',
    },
    {
      title: '计算基数',
      dataIndex: 'basicAmount',
      key: 'basicAmount',
      render: (value: number | null) => value != null ? `¥${value.toFixed(2)}` : '-',
    },
    {
      title: '应交党费',
      dataIndex: 'payableAmount',
      key: 'payableAmount',
      render: (value: number | null) => value != null ? `¥${value.toFixed(2)}` : '-',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
    },
  ];

  return (
    <Card>
      <Form
        form={form}
        layout="inline"
        style={{ marginBottom: 24 }}
      >
        <Form.Item name="keyword" label="关键词">
          <Input placeholder="姓名/身份证号/标识号" allowClear />
        </Form.Item>
        <Form.Item name="className" label="所在班级">
          <Input placeholder="请输入所在班级" allowClear />
        </Form.Item>
        <Form.Item name="position" label="职务">
          <Input placeholder="请输入职务" allowClear />
        </Form.Item>
        <Form.Item name="year" label="年份">
          <Select
            placeholder="请选择年份"
            allowClear
            options={Array.from({ length: 5 }, (_, i) => ({
              label: `${new Date().getFullYear() - i}年`,
              value: new Date().getFullYear() - i,
            }))}
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" onClick={handleSearch}>
              搜索
            </Button>
            <Button onClick={handleReset}>
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>

      <div style={{ marginBottom: 16 }}>
        <Space>
          <Button
            icon={<DownloadOutlined />}
            onClick={handleExport}
          >
            导出
          </Button>
        </Space>
      </div>

      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        loading={loading}
        pagination={pagination}
        onChange={(pagination: TablePaginationConfig) => {
          if (pagination.current && pagination.pageSize) {
            setPagination({
              current: pagination.current,
              pageSize: pagination.pageSize,
              total: pagination.total || 0,
            });
          }
        }}
        scroll={{ x: 1500 }}
      />
    </Card>
  );
};

export default PartyFeeResult; 